#pragma once

#include <iostream>
#include <unordered_map>
#include <fstream>
#include <string>
#include "log.hpp"

#define DICT_DEFAULT_PATH "./dict.txt"

class Dict
{
private:
    void log()
    {
        std::ifstream dict(_dict_path);
        if (!dict.is_open())
        {
            LOG(FATA, "open %s error", _dict_path.c_str());
            exit(1);
        }

        std::string eng_ch;
        std::string seq = ": "; //字典分隔符
        while (std::getline(dict, eng_ch))
        {
            if (eng_ch.empty())    //空行
                continue;

            auto pos = eng_ch.find(seq);
            if (pos == std::string::npos) //没找到分隔符
                continue;

            std::string english = eng_ch.substr(0, pos);
            if (english.empty())    //没有英文
                continue;

            std::string chinese = eng_ch.substr(pos + seq.size());
            if (chinese.empty())   //没有中文
                continue;

            _dict.insert(std::make_pair(english, chinese));
            LOG(DEBUG, "log dict: [%s: %s]", english.c_str(), chinese.c_str());
        }
        dict.close();
        LOG(INFO, "LOG DICT SUCCESS");
    }

public:
    Dict(const std::string &dict_path)
        : _dict_path(dict_path)
    {
        log();
    }

    std::string translate(const std::string& eng)
    {
        auto iter = _dict.find(eng);

        if (iter == _dict.end())
        {
            std::cout << "没有找到" << std::endl;
            return "";
        }

        return iter->second;
    }

private:
    std::string _dict_path;
    std::unordered_map<std::string, std::string> _dict;
};